#include <stdarg.h>
#include <time.h>
#include <sys/types.h>
#include <unistd.h>
#include <assert.h>

#include "mylog.h"

FILE * lfp = NULL;

static const char* lv_lables[] = {"\xE2\x98\x85 [FATAL]","\xE2\x98\x86 [ERROR]", "[LOG]", "[DEBUG]"};

int logon()
{
	assert(lfp == NULL);
	lfp = fopen(MY_LOG_PATH, "a+");
	if(lfp == NULL){
		return -1;
	}
	return 0;
}

int logoff()
{
	return fclose(lfp);
}

int logit(unsigned char level, const char *fmt, ...)
{
	if(lfp == NULL || level > LV_DEBUG){
		return -1;
	}
	if(level > MY_LOG_LEVEL){
		return 0;
	}
//	fprintf(lfp, lv_lables[level]);
	fprintf(lfp, "%s", lv_lables[level]);

	time_t t = time(NULL);
	struct tm tm;
	localtime_r(&t, &tm);
	fprintf(lfp, "[%.2d:%.2d:%.2d %.2d/%.2d][%u]: ", tm.tm_hour, tm.tm_min, tm.tm_sec, tm.tm_mon+1, tm.tm_mday, getpid());
	va_list argp;
	va_start(argp, fmt);
	vfprintf(lfp, fmt, argp);
	va_end(argp);
	fprintf(lfp, "\n");
	return 0;
}
